package org.sanmao.wyj.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.sanmao.wyj.controller.utils.Result;
import org.sanmao.wyj.controller.utils.ResultCode;
import org.sanmao.wyj.domain.*;
import org.sanmao.wyj.service.*;
import org.sanmao.wyj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;



@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ConmentService conmentService;
    @Autowired
    private ComplainService complainService;

// user登录且获取token
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String token = userService.login(user);
        if(token!= null){
            return Result.success(token);
        }
        else return Result.successButNoObject();
    }


//   注册账号
    @PostMapping("/register")
    public Result saveUser(@RequestBody User user){
        if(userService.saveUser(user)){
            return Result.success();
        }
        else return Result.failure(-1,"账号已存在！") ;
    }

    //    个人信息
    @GetMapping
    public Result findMe(HttpServletRequest request){
        return Result.success(userService.findMe(request));
    }

    /**
     * 按type类型查询订单 分页
     * @param type 类型
     * @param request 请求头
     * @param currentPage 当前页
     * @param pageSize 数据条数
     * @return
     */
    @GetMapping(value = "/orders/{currentPage}/{pageSize}",params = {"type"})
    public Result findOrderByType(@RequestParam(value = "type") int type,HttpServletRequest request,@PathVariable int currentPage,@PathVariable int pageSize){
        String token = request.getHeader("token");
        int userId = JwtUtils.getUserId(token);
        return Result.success(orderService.findOrderByUidAndType(userId,type,currentPage,pageSize));
    }


//  按内容模糊查询订单
    @GetMapping(value = "/orders/{currentPage}/{pageSize}",params = {"type","con"})
    public Result fuzzyFindByType(@RequestParam(value = "con") String con,@RequestParam(value = "type")int type,@PathVariable int currentPage,@PathVariable int pageSize,HttpServletRequest request){
        IPage<Order> page = orderService.fuzzyFindOrderByConAndUidAndType(con, type, currentPage, pageSize, request);
        return Result.success(page);
    }

    //  按内容模糊查询订单
    @GetMapping(value = "/orders/{currentPage}/{pageSize}",params = {"state","con"})
    public Result fuzzyFindBystate(@RequestParam(value = "con") String con,@RequestParam(value = "state")int state,@PathVariable int currentPage,@PathVariable int pageSize,HttpServletRequest request){
        IPage<Order> page = orderService.fuzzyFindOrderByConAndUidAndState(con, state, currentPage, pageSize, request);
        return Result.success(page);
    }

//    按state查看订单（页面写死数据，即可换页）
    @GetMapping(value = "/orders/{currentPage}/{pageSize}",params = {"state"})
    public Result findOrderByState(@PathVariable int currentPage,@PathVariable int pageSize,@RequestParam int state,HttpServletRequest request){
      return Result.success(orderService.findOrderByState(currentPage,pageSize,state,request));
    }

    //   根据订单查询worker的电话
    @GetMapping("/findWorkerPhonenum/{oid}")
    public Result findWorkerPhonenum(@PathVariable int oid){
        return Result.success(orderService.findWorkerPhonenumByWid(oid));
    }

//    订单详情
    @GetMapping("/orders/{oid}")
    public Result findFullOrderById(@PathVariable int oid){
       return Result.success(orderService.findFullOrderByOid(oid));
    }


//    评价订单
    @PostMapping("/orders/conments/{oid}")
    public Result addCom(@PathVariable int oid,@RequestBody Conment conment,HttpServletRequest request){
        if(conmentService.addCom(oid,conment,request) == 1){
            return Result.success(1,"评价成功！");
        }
        else {
            return Result.failure(-1,"业务逻辑出现错误，请联系管理员处理！");
        }
    }


//创建订单
    @PostMapping("/orders")
    public Result addOrder(@RequestBody Order order,HttpServletRequest request){
        if(orderService.addOrder(order,request)<0){
            return Result.failure(-1,"余额不足，请充值后再试！");
        }
        else return Result.success(1,"操作成功");
    }

//修改订单
    @PutMapping("/orders")
    public Result updateOrder(@RequestBody Order order){
        return Result.success(orderService.updateById(order));
    }


//删除订单
    @DeleteMapping("/orders/{oid}")
    public Result deleteOrderByid(@PathVariable int oid){
        if(orderService.deleteOrderByOid(oid)){
            return Result.success(1,"删除成功！");
        }
        return Result.failure(-1,"删除失败，请联系管理员！");
    }
//编辑个人信息
    @PutMapping
    public Result updateUser(@RequestBody User user,HttpServletRequest request){
        if(userService.updateUser(user,request)){
            return Result.success();
        }
        else return Result.failure(-1,"已经有该用户了！");
    }
//    找回密码
    @PutMapping("/resetpassword")
    public Result findPassword(@RequestParam String username,@RequestParam String phonenum,@RequestParam String password){
        if(userService.findPassword(username,phonenum,password)){
            return Result.success(true);
        }
        else return Result.failure(ResultCode.USER_NOT_EXIST);
    }
//留言
    @PostMapping("/messages")
    public Result addMsg(@RequestBody Message msg, HttpServletRequest request){
        return Result.success(messageService.saveMsg(msg,request));
    }

//查询留言
    @GetMapping("/messages/{currentPage}/{pageSize}")
    public Result findMsg(@PathVariable int currentPage,@PathVariable int pageSize){
        IPage<Message> page = new Page(currentPage,pageSize);
        return Result.success(messageService.page(page));
    }

//删除留言
    @DeleteMapping("/messages/{mid}")
    public Result delMsgById(@PathVariable int mid,HttpServletRequest request){
        if(messageService.userDelMsgById(mid,request)){
            return Result.success(true);
        }
        else return Result.failure(-1,"不能删除非自己的留言！");
    }

//充值
    @PutMapping("/addmoney")
    public Result updateMoney(@RequestParam double balance,HttpServletRequest request){
        if(userService.addMoney(balance,request) == 1)
        {
            return Result.success(1,"充值成功！");
        }
        else return Result.failure(-1,"充值失败，请联系管理员处理！");
    }

//投诉
    @PostMapping("/orders/complain/{oid}")
    public Result addComplain(@PathVariable int oid,@RequestBody Complain complain,HttpServletRequest request){
        if(complainService.addComplain(oid,complain,request)){
            return Result.success();
        }else return Result.failure(-1,"请联系管理员");
    }

}
